package com.ls.herostory.mq;

import com.alibaba.fastjson.JSONObject;
import com.ls.herostory.rank.RankRedisManager;
import com.rabbitmq.client.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.concurrent.*;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2020/10/14 15:56
 * @since
 */
public class MqConsumer {
    private final static Logger logger = LoggerFactory.getLogger(MqConsumer.class);

    private static MqConsumer mqProducer = new MqConsumer();

    private Channel channel;

    private MqConsumer(){
        try{
            init();
        }catch (Exception e){
            logger.error(e.getMessage(), e);
        }
    }

    public static MqConsumer getInstance(){
        return mqProducer;
    }

    private void init(){
        ConnectionFactory connectionFactory = MqConnectionFactoryUtil.getConnectionFactory();
        try {
            Connection connection = connectionFactory.newConnection();

            channel = connection.createChannel();

            // 定义交换机
            channel.exchangeDeclare("rank", "fanout", true, false, null);
            // 定义队列
            channel.queueDeclare("rank", true, false, false, null);
            // 队列绑定交换机
            channel.queueBind("rank", "rank", "#");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public void startConsumer() {
        try {
            DefaultConsumer rankMqConsumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    try{
                        String json = new String(body);
                        logger.info("receive mq msg: {}", json);
                        AttkMsg msg = JSONObject.parseObject(json, AttkMsg.class);

                        RankRedisManager.getIntance().updateScore(msg);

                        // ack确认
                        getChannel().basicAck(envelope.getDeliveryTag(), false);
                    }catch (Exception e){
                        getChannel().basicNack(envelope.getDeliveryTag(), false, true);
                        logger.error(e.getMessage(), e);
                    }
                }
            };

            channel.basicConsume("rank", false, "rank-startConsumer-01", rankMqConsumer);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
